package com.common.util;

import java.io.RandomAccessFile;
import java.security.MessageDigest;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang.StringUtils;
import org.apache.struts2.ServletActionContext;
import org.springframework.security.core.context.SecurityContextHolder;

import com.manage.auth.MyInvocationSecurityMetadataSource;
import com.model.auth.User;
/**
 * 常用工具类
 * @author Administrator
 *
 */
public class Tools {
	/**
	 * 记录错误日志，写文件ManagerError.log
	 */
	public static final String ERRORLOG = "nzserror";
	/**
	 * 记录信息日志，不写文件，只打印到控制台
	 */
	public static final String INFOLOG = "nzsinfo";
	/**
	 * 记录操作日志，写文件OperateInfo.log
	 */
	public static final String INFOLOG2FILE = "nzsinfo2file";
	/**
	 * 记录信息日志，普通打印写文件ManagerInfo.log
	 */
	public static final String INFOLOG3FILE = "nzsinfo3file";

	public static final String LUCENE_ERRORLOG = "luceneerror";

	private static Calendar cal = Calendar.getInstance();

	
	public static User getCurrentUser(){
		
		return (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
	}
	
	
	/**
	 * 清楚缓存中的权限对象
	 */
	public static void cleanResource(){
		
		MyInvocationSecurityMetadataSource.cleanResource();
	}
	
	/**
	 * 给日期增加/减少天数
	 * 
	 * @param days
	 *          需要增加的天数
	 * @param date
	 *          日期
	 * @return
	 */
	public static Date addDays(int days, Date date) {
		cal.setTime(date);
		cal.add(Calendar.DATE, days);
		return cal.getTime();
	}

	/**
	 * 给日期增加/减少分钟数
	 * 
	 * @param minutes
	 *          需要增加的分钟数
	 * @param date
	 *          日期
	 * @return
	 */
	public static Date addMinutes(int minutes, Date date) {
		cal.setTime(date);
		cal.add(Calendar.MINUTE, minutes);
		return cal.getTime();
	}

	/**
	 * 判断当前是否月底
	 * 
	 * @param date
	 * @return
	 */
	public static boolean isEndDay(Date date) {
		cal.setTime(date);
		cal.set(Calendar.DATE, cal.get(Calendar.DAY_OF_MONTH) + 1);
		if (cal.get(Calendar.DAY_OF_MONTH) == 1) {
			return true;
		}
		return false;
	}

	/**
	 * 判断当前是周几
	 * 
	 * @param date
	 * @return
	 */
	public static int dayForWeek(Date date) {
		cal.setTime(date);
		int dayForWeek = 0;
		if (cal.get(Calendar.DAY_OF_WEEK) == 1) {
			dayForWeek = 7;
		} else {
			dayForWeek = cal.get(Calendar.DAY_OF_WEEK) - 1;
		}
		return dayForWeek;
	}
	/**
	 * 判断当前是几号
	 * @param date
	 * @return
	 */
	public static int dayForMonth(Date date) {
		cal.setTime(date);
		return cal.get(Calendar.DAY_OF_MONTH);
	}

	/**
	 * 字符串转日期 yyyy-MM-dd HH:mm:ss
	 * 
	 * @return Date
	 * @throws ParseException
	 */
	public static Date stringToDate(String str) throws ParseException {
		if (StringUtils.isBlank(str)) {
			return null;
		}
		Date date = null;
		DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		date = df.parse(str);
		return date;

	}

	/**
	 * 字符串转日期 yyyy-MM-dd
	 * 
	 * @return Date
	 * @throws ParseException
	 */
	public static Date stringToDate2(String str) throws ParseException {
		if (StringUtils.isBlank(str)) {
			return null;
		}
		Date date = null;
		DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
		date = df.parse(str);
		return date;

	}

	/**
	 * 日期转换字符串:yyyy年MM月dd日
	 * 
	 * @param date
	 * @return
	 */
	public static String dateToString(Date date) {
		if (date == null) {
			return null;
		}
		DateFormat df = new SimpleDateFormat("yyyy年MM月dd日");
		return df.format(date);

	}

	/**
	 * 日期转换字符串:yyyyMMdd
	 * 
	 * @param date
	 * @return
	 */
	public static String date2String(Date date) {
		if (date == null) {
			return null;
		}
		DateFormat df = new SimpleDateFormat("yyyyMMdd");
		return df.format(date);

	}

	/**
	 * 日期转换字符串:yyyy-MM-dd
	 * 
	 * @param date
	 * @return
	 */
	public static String date2String5(Date date) {
		if (date == null) {
			return null;
		}
		DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
		return df.format(date);

	}

	/**
	 * 日期转换字符串:yyyy-MM-dd HH:mm
	 * 
	 * @param date
	 * @return
	 */
	public static String date2String6(Date date) {
		if (date == null) {
			return null;
		}
		DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm");
		return df.format(date);

	}

	/**
	 * 日期转换字符串:yyyy-MM-dd HH:mm:ss
	 * 
	 * @param date
	 * @return
	 */
	public static String date2String2(Date date) {
		if (date == null) {
			return null;
		}
		DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		return df.format(date);

	}

	/**
	 * 日期转换字符串:yyyy.MM.dd
	 * 
	 * @param date
	 * @return
	 */
	public static String date2String3(Date date) {
		if (date == null) {
			return null;
		}
		DateFormat df = new SimpleDateFormat("yyyy.MM.dd");
		return df.format(date);

	}

	/**
	 * 日期转换字符串:yyyyMMddHHmmss
	 * 
	 * @param date
	 * @return
	 */
	public static String date2String4(Date date) {
		if (date == null) {
			return null;
		}
		DateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
		return df.format(date);

	}

	/**
	 * 日期转换字符串:MM月dd日
	 * 
	 * @param date
	 * @return
	 */
	public static String date2String7(Date date) {
		if (date == null) {
			return null;
		}
		DateFormat df = new SimpleDateFormat("MM-dd");
		return df.format(date);

	}
	
	/**
	 * 日期转换字符串:yyyy-MM-dd HH:mm
	 * 
	 * @param date
	 * @return
	 */
	public static String date2String8(Date date) {
		if (date == null) {
			return null;
		}
		DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm");
		return df.format(date);

	}

	/**
	 * 判断是否数字
	 * 
	 * @param str
	 * @return
	 */
	public static boolean isNumeric(String str) {
		for (int i = str.length(); --i >= 0;) {
			if (!Character.isDigit(str.charAt(i))) {
				return false;
			}
		}
		return true;
	}

	/**
	 * 金额转换字符串 "##0.000"
	 * 
	 * @param d
	 * @return
	 */
	public static String moneyToString(double d) {
		java.text.DecimalFormat df = new java.text.DecimalFormat("##0.000");
		return df.format(d);
	}

	/**
	 * ##0.0000
	 * 
	 * @param d
	 * @return
	 */
	public static String rateToString(double d) {
		java.text.DecimalFormat df = new java.text.DecimalFormat("##0.0000");
		return df.format(d);
	}

	/**
	 * 格式化百分比#0.00#%
	 * 
	 * @param d
	 * @return
	 */
	public static String baiFenBiToString(double d) {
		java.text.DecimalFormat df = new java.text.DecimalFormat("#%");
		return df.format(d);
	}

	/**
	 * 取当前时间
	 * 
	 * @param currentDate
	 * @return "HH:mm"
	 */
	public static String getTime(Date currentDate) {
		DateFormat dfDateTime = new SimpleDateFormat("HH:mm");
		return dfDateTime.format(currentDate);
	}

	// /**
	// * 获取前一天的日期
	// * @return
	// */
	// public static String getBeforeDate(){
	// cal.add(Calendar.DAY_OF_MONTH, -1);
	// SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
	// return sdf.format(cal.getTime());
	// }

	/**
	 * 获取指定时间的前30分钟的时间
	 */
	public static Date getBefore30Minute(Date currentDate) {
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(currentDate);
		calendar.add(Calendar.MINUTE, -30);
		return calendar.getTime();
	}

	/**
	 * 获取当天00：00：00时间
	 * 
	 * @param currentDate
	 * @return
	 */
	public static Date getDayOfStartTime(Date currentDate) {
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(currentDate);
		calendar.set(Calendar.HOUR_OF_DAY, 0);
		calendar.set(Calendar.MINUTE, 0);
		calendar.set(Calendar.SECOND, 0);
		return calendar.getTime();
	}

	/**
	 * 得到请求参数
	 * 
	 * @author xieyp
	 * @param key
	 *          String
	 * @return String
	 */
	public static String getParameter(String key) {
		if (key == null) {
			return null;
		}
		return getRequest().getParameter(key); // Mod [1.21]
	}

	/**
	 * 得到request
	 * 
	 * @author xieyp
	 * @return HttpServletRequest
	 */
	public static HttpServletRequest getRequest() {
		HttpServletRequest request = ServletActionContext.getRequest();
		return request;
	}

	/**
	 * 得到session
	 * 
	 * @author xieyp
	 * @return HttpSession
	 */
	public static HttpSession getSession() {
		HttpSession session = null;
		try {
			HttpServletRequest request = getRequest();
			session = request.getSession();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return session;
	}

	/**
	 * 获取月份(yyyy-MM-dd)
	 * 
	 * @param dateStr
	 * @return
	 * @throws ParseException
	 */
	public static String getMonth(String dateStr) throws ParseException {
		DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
		Date date = df.parse(dateStr);
		return String.valueOf(date.getMonth() + 1);
	}

	/**
	 * 获取年份
	 * 
	 * @param date
	 * @return
	 * @throws ParseException
	 */
	public static String getYear(Date date) throws ParseException {
		cal.setTime(date);
		return String.valueOf(cal.get(cal.YEAR));
	}

	/**
	 * 获取天数
	 * 
	 * @param dateStr
	 * @return
	 * @throws ParseException
	 */
	public static String getDay(String dateStr) throws ParseException {
		DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
		Date date = df.parse(dateStr);
		cal.setTime(date);
		return String.valueOf(cal.get(cal.DAY_OF_MONTH));
	}

	/**
	 * 格式化路径"/"为"》"
	 * 
	 * @param path
	 * @return
	 * @throws Exception
	 */
	public static String formatPath(String path, boolean flag) throws Exception {
		String s = path.replaceAll("\\\\", "/");
		String filePathView = "";
		if (flag) {
			if (s.lastIndexOf("/") == 2) {
				filePathView = s.substring(2);
			} else {
				filePathView = s.substring(2, s.lastIndexOf("/"));
			}
		} else {
			filePathView = s.substring(2);
		}
		return filePathView.replaceAll("/", "》");
	}

	/**
	 * 格式化文件名，替换："(" ")"和空格
	 * 
	 * @param fileName
	 * @return
	 * @throws Exception
	 */
	public static String formatFileName(String fileName) {
		if (StringUtils.isNotBlank(fileName)) {
			Pattern p = Pattern.compile("[\\s+(+)+]");
			Matcher m = p.matcher(fileName);
			fileName = m.replaceAll("_");
		}
		return fileName;
	}

	
	public static String renameFile2(String fileName) {
		if (StringUtils.isNotBlank(fileName)) {
			Random r = new Random();
			int rannum = (int) (r.nextDouble() * (999 - 100 + 1)) + 100; // 获取随机数
			// 获取拓展名
			String extName = "";
			if (fileName.lastIndexOf(".") >= 0) {
				extName = fileName.substring(fileName.lastIndexOf("."));
				extName = extName.toLowerCase();
			}

				String fn = fileName.substring(0, fileName.lastIndexOf("."));
				return fn + "_" + rannum + extName; // 文件重命名后的名字
		}
		return null;
	}

//	/**
//	 * 获取时间路径：yyyyMMdd/
//	 * 
//	 * @return
//	 */
//	public String getDatePath() {
//		Date d = new Date();
//		return Tools.date2String(d) + "/";
//	}

	/**
	 * 访问连接
	 * 
	 * @param url
	 * @return
	 */
	// public static int responseUrl(String url){
	// HttpClient httpclient = new DefaultHttpClient();
	// int status = 0;
	// if(StringUtils.isNotBlank(url)){
	// // String url = CDN_Path+"/"+am.getDownloadUrl();
	// try {
	// // 创建httpPost
	// HttpGet httpPost = new HttpGet(url);
	//				
	// //执行POST请求.
	// HttpResponse response = httpclient.execute(httpPost);
	// //返回执行状态
	// status = response.getStatusLine().getStatusCode();
	//				
	// }catch (Exception ex){
	// errorLog.error(ex.getMessage(),ex);
	// } finally {
	// httpclient.getConnectionManager().shutdown();
	// }
	// }
	// return status;
	// }

	/**
	 * 获取文件内容长度
	 * 
	 * @param file
	 * @return
	 * @throws Exception
	 */
	public static long fileLength(String file) throws Exception {
		RandomAccessFile raf = new RandomAccessFile(file, "rw");// rw为读写模式
		long length = raf.length();
		raf.close();
		return length;
	}
	
	/**
	 * MD5加密
	 * @param str
	 * @return
	 */
	public static String md5Encode(String str) {
		StringBuffer buf = new StringBuffer();
		try {
			MessageDigest md5 = MessageDigest.getInstance("MD5");
			md5.update(str.getBytes());
			byte bytes[] = md5.digest();
			for (int i = 0; i < bytes.length; i++) {
				String s = Integer.toHexString(bytes[i] & 0xff);
				if (s.length() == 1) {
					buf.append("0");
				}
				buf.append(s);
			}

		} catch (Exception ex) {
		}
		return buf.toString();
	}
	
	
	public static void main(String[] args) {
		try {
			// FileWriter raf = new FileWriter
			// ("D:/开发/其他/amcharts报表/amstock_1.1.7.2/amstock_1.1.7.2/amstock/data.csv",
			// true);//rw为读写模式
			// raf.flush();
			// raf.close();
			// double d = 0/Double.valueOf(786);
			// System.out.println(d);
			// System.out.println(Math.round(d*100)/100D);
			System.out.println(Tools.getSession());
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
